<!--  -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px;">
      <div class="header">
        <el-button type="primary" @click="parameterConfiguration">参数配置</el-button>
        <el-button type="primary" @click="refresh">刷新</el-button>
        <el-button type="primary" @click="toggleFullScreen">
          {{ isFullScreen ? '退出全屏' : '全屏' }}
        </el-button>
      </div>
      <div class="main">
        <div class="scroll-container">
          <div class="row" v-for="(rowData, rowIndex) in gridData" :key="rowIndex" :style="rowStyle">
            <div class="block" v-for="(item, colIndex) in rowData" :key="colIndex" :style="blockStyle(item)"
              @click="toggleBlockFullScreen($event)">
              <el-image v-if="item" :src="item.ResFileName" fit="fill" :key="item.TransTime"></el-image>
              <div v-else class="empty-block">无数据</div>
              <div class="time" v-if="item">
                <p>{{ item.Department }}</p>
                <p>{{ item.DeviceName }}</p>
                <p>{{ parseTime(item.TransTime) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="参数配置" top="5vh"
      :visible.sync="dialogVisible" v-el-drag-dialog width="50%">
      <el-form label-width="120px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">基本规则内容</el-divider>
          <el-form-item label='自动刷新：' prop="Capture">
            <el-checkbox v-model="accountForm.Capture" :true-label="1" :false-label="0">开启</el-checkbox>
            自动播放时间间隔：<el-input v-model.number="accountForm.CatInterval" style="width:200px" @input="restrictNumberInput"
              maxlength="2" placeholder="请输入大于0的数字"></el-input> 秒
          </el-form-item>
          <el-form-item label="屏幕显示：">
            <grid-selector @update-selection="updateGridSelection" :initial-rows="accountForm.Row"
              :initial-cols="accountForm.Column" />
          </el-form-item>
          <device-object-selector :form.sync="accountForm" />
          <el-form-item label='排序模式：' prop="Polling">
            <!-- <el-checkbox v-model="accountForm.Polling" :true-label="1" :false-label="0">开启</el-checkbox> （选择资产数量超过屏幕数量轮播） -->
            <el-radio v-model="accountForm.Polling" :label="1">按最近采集时间排序</el-radio>
            <el-radio v-model="accountForm.Polling" :label="0">按资产名称排序</el-radio>
          </el-form-item>
          <el-form-item label='超时次数：' prop="Capture">
            <div style="display: flex; align-items: center;">
              <!-- 红色圆圈感叹号图标 -->
              <el-tooltip content="配置为0时不启用，配置为非0时，超过此次数未上送的数据不显示" placement="top">
                <span class="exclamationPoint">
                  !
                </span>
              </el-tooltip>
              <!-- 下拉选择框 -->
              <el-select v-model="accountForm.TimeOut">
                <el-option :value="0" label="不开启"></el-option>
                <el-option :value="3" label="3次"></el-option>
                <el-option :value="5" label="5次"></el-option>
                <el-option :value="10" label="10次"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label='独立获取：' prop="Independence">
            <div style="display: flex; align-items: center;">
              <!-- 红色圆圈感叹号图标 -->
              <el-tooltip content="不勾选表示使用最近录制的屏幕视频，勾选则实时获取屏幕。" placement="top">
                <span class="exclamationPoint">
                  !
                </span>
              </el-tooltip>
              <el-checkbox v-model="accountForm.Independence" :true-label="1" :false-label="0">开启</el-checkbox>
            </div>
          </el-form-item>
          <!-- <el-form-item label='固定资产显示：' prop="Polling">
            <el-radio v-model="accountForm.UseFixed" @change="UseFixedChange" :label="0">不固定显示</el-radio>
            <el-radio v-model="accountForm.UseFixed" @change="UseFixedChange" :label="1">固定资产显示</el-radio>
            <el-cascader style="width:100%;" placeholder="请选择资产" ref="fixedAssets" v-model="accountForm.FixedObj"
              :options="deviceObjList" :props="cascaderProps" />
          </el-form-item> -->
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import GridSelector from './components/GridSelector.vue'
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
import { connrequest } from '@/api/firstPage'
import { parseTime, GetDeviceTree } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  components: {
    GridSelector,
    DeviceObjectSelector
  },
  directives: { elDragDialog },
  data() {
    return {
      dialogVisible: false,
      accountForm: {
        Capture: 0,
        CatInterval: 0,
        Row: 3,
        Column: 3,
        DeviceObjType: 1,
        DeviceObj: '',
        Polling: 0,
        UseFixed: 0,
        TimeOut: 0,
        FixedObj: []
      },
      rules: {
        CatInterval: [
          { validator: this.validateCatInterval, trigger: 'blur' }
        ]
      },
      deviceObjList: [],
      RoleList: [],
      AssetsList: [],
      screenData: [], // 存储后端数据的数组
      containerWidth: 0,
      containerHeight: 0,
      isFullScreen: false,
      refreshInterval: null,
      cascaderProps: {
        children: 'Children',
        label: 'Name',
        value: 'ID',
        emitPath: false,
        multiple: true,
        checkStrictly: false,
      }
    }
  },
  computed: {
    rowStyle() {
      return {
        display: 'flex',
        'flex-wrap': 'nowrap',
        height: `${100 / this.accountForm.Row}%`,
      };
    },
    blockStyle() {
      return (item) => ({
        width: `${this.containerWidth / this.accountForm.Column}px`,
        height: `${this.containerHeight / this.accountForm.Row}px`,
        border: '1px dashed #666',
        backgroundColor: item ? '#e6f7ff' : 'transparent',
      });
    },
    gridData() {
      const totalBlocks = this.accountForm.Row * this.accountForm.Column;
      let dataToDisplay = this.screenData.slice(0, totalBlocks);
      while (dataToDisplay.length < totalBlocks) {
        dataToDisplay.push(null);
      }
      const grid = [];
      for (let i = 0; i < this.accountForm.Row; i++) {
        const start = i * this.accountForm.Column;
        const end = start + this.accountForm.Column;
        grid.push(dataToDisplay.slice(start, end));
      }
      return grid;
    },
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.initializeAccountForm();
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.updateContainerSize();
    window.addEventListener('resize', this.updateContainerSize);
    if (this.accountForm.Capture) this.startAutoRefresh();
    document.addEventListener('fullscreenchange', this.handleFullScreenChange);
    // let baseUrl = this.extractBaseUrl(window.location.href);
    // window.open(`${baseUrl}realTimeScreen`)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updateContainerSize);
    document.removeEventListener('fullscreenchange', this.handleFullScreenChange);
    if (this.refreshInterval) clearInterval(this.refreshInterval);
  },
  methods: {
    parseTime,
    // 限制输入只能为数字
    restrictNumberInput(value) {
      // 只保留数字，移除非数字字符
      const numValue = value.replace(/[^\d]/g, '')
      // 更新 v-model 值
      this.accountForm.CatInterval = numValue ? Number(numValue) : ''
    },

    // 校验 CatInterval 必须大于0
    validateCatInterval(rule, value, callback) {
      if (!value && value !== 0) {
        callback(new Error('请输入时间间隔'))
      } else if (value <= 0) {
        callback(new Error('时间间隔必须大于0'))
      } else {
        callback()
      }
    },
    async initializeAccountForm() {
      try {
        const data = {
          Filter: {
            FileName: 'param_real_screen.json'
          }
        };
        const res = await connrequest('GetUICommonParam', data);
        if (res && res.Data) {
          this.accountForm = { ...this.accountForm, ...res.Data }; // 合并后端数据，保留默认值
          this.startAutoRefreshInterval()
        }
      } catch (error) {
        console.error('初始化 accountForm 失败:', error);
      }
    },
    startAutoRefreshInterval() {
      // 清除已有定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
      // 如果 Capture 为 0，则不启动刷新
      if (this.accountForm.Capture === 0) {
        return
      }
      // 设置刷新间隔，默认 3 秒（3000 毫秒）
      const interval = (this.accountForm.CatInterval > 0 ? this.accountForm.CatInterval : 3) * 1000
      // 启动自动刷新
      this.refreshInterval = setInterval(() => {
        this.getData()
      }, interval)
    },
    updateGridSelection({ rows, cols }) {
      this.accountForm.Row = rows
      this.accountForm.Column = cols
    },
    extractBaseUrl(fullUrl) {
      const index = fullUrl.indexOf('#/');
      if (index !== -1) {
        return fullUrl.substring(0, index + 2); // 截取到 #/
      }
      return fullUrl; // 如果没有 #/，返回完整 URL
    },
    async parameterConfiguration() {
      await this.initData()
      const data = {
        Filter: {
          FileName: 'param_real_screen.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.dialogVisible = true
      this.accountForm = { ...this.accountForm, ...res.Data }
    },
    refresh() {
      this.getData()
    },
    async submit() {
      if (!this.accountForm.CatInterval || this.accountForm.CatInterval < 1) {
        this.$message.info('请输入自动播放时间间隔,最小时间间隔为1秒')
        return
      }
      const data = {
        Filter: {
          FileName: 'param_real_screen.json'
        },
        Data: {
          ...this.accountForm
        }
      }
      const res = await connrequest('SetUICommonParam', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.getData()
        this.startAutoRefreshInterval();
      }
    },
    async getData() {
      const res = await connrequest('GetRealTimeScreenLog')
      // 处理 ResFileName，去掉 /school/nodejs 前缀
      this.screenData = res.Data.map(item => {
        let url = `${item.ResFileName.replace('/school/nodejs/public', '')}?t=${item.TransTime}`
        item.ResFileName = url
        return item
      });
      this.screenData = res.Data;
    },
    async UseFixedChange(value) {
      if (value === 1) {
        await this.initData()
      }
    },
    async initData(searchobj = {}) {
      try {
        const { DeviceTree } = await GetDeviceTree()
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    // 将设备数据转换为 el-cascader 树结构的函数
    generateCascaderTree(devices, departments) {
      // 第一步：按 DepartmentID 分组设备
      const deviceMap = devices.reduce((acc, device) => {
        const deptId = device.DepartmentID
        if (!acc[deptId]) {
          acc[deptId] = []
        }
        acc[deptId].push({
          ID: device.DeviceUUID,  // 使用 DeviceUUID 作为唯一标识
          Name: device.DeviceName,
          leaf: true  // 标记为叶子节点
        })
        return acc
      }, {})

      // 第二步：构建树结构
      const tree = departments.map(dept => {
        return {
          ID: dept.ID,
          Name: dept.Name,
          Children: deviceMap[dept.ID] || [],  // 如果该部门没有设备，返回空数组
          leaf: false  // 部门是非叶子节点
        }
      })

      return tree
    },
    updateContainerSize() {
      if (!this.isFullScreen) {
        const mainElement = document.querySelector('.main');
        if (mainElement) {
          // 获取父容器（假设是 .el-row 或 .dashboard-editor-container）的实际高度
          const parentElement = mainElement.parentElement;
          const headerHeight = document.querySelector('.header')?.offsetHeight || 0;
          const buttonsHeight = 78; // 假设按钮区域高度为 50px，需根据实际测量调整
          const padding = 32; // 考虑 padding (16px * 2)

          // 计算可用高度
          const availableHeight = parentElement.offsetHeight - headerHeight - buttonsHeight - padding;
          this.containerHeight = availableHeight > 0 ? availableHeight : (window.innerHeight - headerHeight - buttonsHeight - padding);
          this.containerWidth = mainElement.offsetWidth;
        }
      } else {
        this.containerWidth = window.innerWidth;
        this.containerHeight = window.innerHeight;
      }
    },
    toggleFullScreen() {
      const dashboardContainer = document.querySelector('.dashboard-editor-container');
      if (!this.isFullScreen) {
        if (dashboardContainer.requestFullscreen) {
          dashboardContainer.requestFullscreen();
        } else if (dashboardContainer.mozRequestFullScreen) {
          dashboardContainer.mozRequestFullScreen();
        } else if (dashboardContainer.webkitRequestFullscreen) {
          dashboardContainer.webkitRequestFullscreen();
        } else if (dashboardContainer.msRequestFullscreen) {
          dashboardContainer.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },
    toggleBlockFullScreen(event) {
      const block = event.currentTarget;
      if (!document.fullscreenElement) {
        if (block.requestFullscreen) {
          block.requestFullscreen();
        } else if (block.mozRequestFullScreen) {
          block.mozRequestFullScreen();
        } else if (block.webkitRequestFullscreen) {
          block.webkitRequestFullscreen();
        } else if (block.msRequestFullscreen) {
          block.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },
    handleFullScreenChange() {
      this.isFullScreen = !!document.fullscreenElement;
      this.updateContainerSize(); // 更新尺寸

      const dashboardContainer = document.querySelector('.dashboard-editor-container');
      const elRow = document.querySelector('.el-row');
      const mainElement = document.querySelector('.main');
      const scrollContainer = document.querySelector('.scroll-container');
      const header = dashboardContainer.querySelector('.header');

      if (this.isFullScreen) {
        // 全屏时完全铺满视口，确保无间隙
        dashboardContainer.style.position = 'fixed';
        dashboardContainer.style.top = '0';
        dashboardContainer.style.left = '0';
        dashboardContainer.style.width = '100vw';
        dashboardContainer.style.height = '100vh';
        dashboardContainer.style.margin = '0';
        dashboardContainer.style.padding = '0';
        dashboardContainer.style.background = '#fff';

        elRow.style.position = 'absolute';
        elRow.style.top = '0';
        elRow.style.left = '0';
        elRow.style.width = '100%';
        elRow.style.height = '100%';
        elRow.style.padding = '0';
        elRow.style.margin = '0';
        elRow.style.background = 'transparent';

        header.style.display = 'none';
        mainElement.style.position = 'absolute';
        mainElement.style.top = '0';
        mainElement.style.left = '0';
        mainElement.style.width = '100%';
        mainElement.style.height = '100%';
        mainElement.style.margin = '0';
        mainElement.style.padding = '0';
        mainElement.style.background = 'transparent';

        scrollContainer.style.position = 'absolute';
        scrollContainer.style.top = '0';
        scrollContainer.style.left = '0';
        scrollContainer.style.width = '100%';
        scrollContainer.style.height = '100%';
        scrollContainer.style.overflow = 'hidden';
        scrollContainer.style.background = 'transparent';

        // 强制更新高度，确保无空白
        this.containerHeight = window.innerHeight;
      } else {
        // 退出全屏时恢复默认样式
        dashboardContainer.style.position = '';
        dashboardContainer.style.top = '';
        dashboardContainer.style.left = '';
        dashboardContainer.style.width = '';
        dashboardContainer.style.height = '';
        dashboardContainer.style.margin = '';
        dashboardContainer.style.padding = '';
        dashboardContainer.style.background = '';

        elRow.style.position = '';
        elRow.style.top = '';
        elRow.style.left = '';
        elRow.style.width = '';
        elRow.style.height = 'calc(100vh - 86px)';
        elRow.style.padding = '16px';
        elRow.style.margin = '';
        elRow.style.background = '';

        header.style.display = 'flex';
        mainElement.style.position = '';
        mainElement.style.top = '';
        mainElement.style.left = '';
        mainElement.style.width = '';
        mainElement.style.height = '';
        mainElement.style.margin = '';
        mainElement.style.padding = '';
        mainElement.style.background = '';

        scrollContainer.style.position = '';
        scrollContainer.style.top = '';
        scrollContainer.style.left = '';
        scrollContainer.style.width = '';
        scrollContainer.style.height = '';
        scrollContainer.style.overflow = 'auto';
        scrollContainer.style.background = '';

        // 恢复非全屏高度
        this.updateContainerSize();
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  height: 100%;
  width: 100%;
}

.header {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border: 1px solid #E4E7ED;
  padding: 10px;
}

.main {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  border: none;
}

.scroll-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0;
}

.exclamationPoint {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background-color: #ff4d4f;
  border-radius: 50%;
  color: white;
  font-size: 12px;
  margin-right: 8px;
  cursor: pointer;
}

.row {
  width: 100%;

  .block {
    box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);
    position: relative;
    cursor: pointer;

    .el-image {
      width: 100%;
      height: 100%;
      object-fit: fill;
    }

    .time {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      padding: 5px 10px;
      background: rgba(0, 0, 0, 0.5);
      color: #FFFFFF;
      font-size: 14px;
      text-align: center;
      z-index: 1;
      display: flex;
      justify-content: space-between;
      width: auto;

      p {
        margin: 0 10px;
        white-space: nowrap;
      }
    }

    .empty-block {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #000;
      color: #fff;
      font-size: 16px;
    }
  }
}

/* 美化滚动条 */
.scroll-container::-webkit-scrollbar {
  width: 8px;
}

.scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.scroll-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 确保 body 和 html 无默认间距 */
body,
html {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

/* 全屏时确保无间隙 */
.fullscreen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  margin: 0 !important;
  padding: 0 !important;
}
</style>